/* eslint-disable */
import { observable, action, runInAction, makeObservable, makeAutoObservable } from 'mobx'
import { login, register } from '@/api/login'
import { queryMessageCount } from '@/api/message'
import Cookies from 'js-cookie'

class Store {

  constructor() {

    makeAutoObservable(this)

  }

  @observable loadingText = '正在加载'
  @observable loginStatus = false
  @observable userInfo = {}
  @observable unReadMessageCount = 0
  @observable keepState = {}
  // 获取数据源
  @action Login = async (params = {}, callback) => {
    try {
      runInAction(async () => {
        let res = await login(params)
        if (res.code == 200) {
          this.userInfo = res.userInfo;
          Cookies.set('userInfo', res.userInfo, { expires: 3 })
          this.loginStatus = true
        }
        callback(res)
        console.log('看到了错误')
      })
    } catch (error) {
      console.log('看到了错误')
      return Promise.reject('错误')
    }
  }

  @action setUserInfo = async userInfo => {
    this.userInfo = userInfo

    Cookies.set('userInfo', userInfo)
    this.loginStatus = true
  }
  @action loginOut = async () => { // 退出登录
    this.loginStatus = false
    this.userInfo = {}
    Cookies.remove('userInfo')
  }

  @action queryMessage = async (userId, callback) => {
    try {
      runInAction(async () => {
        const res = await queryMessageCount(this.userInfo.userId)
        if (res.code == 200) {
          console.log('拿到消息了')
          this.unReadMessageCount = res.count
          return res.count
        }
      })
    } catch (err) {
      console.log(err)
    }

  }
  @action addKeepState = (name, params) => {
    let obj = this.keepState
    obj[name] = params
    this.keepState = obj
  }
}
export default new Store()
